import Router from "koa-router";

import { DecoratorKey, MethodMetadata } from "../decorator";
import { registerRouter } from "./loadController";




export function loadRoutes(router: Router) {
    
    registerRouter((Controller) => {
        // 获取类的装饰器元数据
        let { prefix } = Reflect.getMetadata(DecoratorKey.Controller, Controller) || {};

        const Prototype = Controller.prototype;

        Object.getOwnPropertyNames(Prototype).forEach(key => {
            // 构造函数去掉
            if (key === "constructor") {
                return;
            }
            // 获取类函数的装饰器元数据
            const config: MethodMetadata = Reflect.getMetadata(DecoratorKey.Method, Prototype, key);
            let { method, route, fn } = config || {};
            // 没有method方法的可以不用管
            if (!method) {
                return;
            }

            const path = prefix + route;

            console.log(`add a ${method} Router: `, path);
            // 添加路由
            router[method](path, async (ctx) => {
                // 如果添加了参数装饰器，这里可以将参数取出然后传给fn函数
                // 同理，如果这里有参数校验装饰器，可以判断参数校验后决定是否执行fn函数进行参数校验
                let body = fn(ctx);

                if (body) {
                    ctx.body = body;
                }
            })
        });
    });
}